package com.example.springboot_code_read.validate;

import com.example.springboot_code_read.bean.MyBean;
import org.springframework.validation.*;

public class ValidateTest {

    public static void main(String[] args) {

        MyBean myBean = new MyBean();
        myBean.setId(-1);
        myBean.setName("1223");

        BeanPropertyBindingResult result = new BeanPropertyBindingResult(myBean, "myBean");

        MyBeanValidate validate = new MyBeanValidate();

        if (validate.supports(MyBean.class)) {
            validate.validate(myBean, result);
        }

        if (result.hasErrors()) {

            for (FieldError error : result.getFieldErrors()) {
                System.out.println(error.getField() + ":" + error.getDefaultMessage());
            }

        }

    }

    static class MyBeanValidate implements Validator {


        @Override
        public boolean supports(Class<?> clazz) {
            return MyBean.class.equals(clazz);
        }

        @Override
        public void validate(Object target, Errors errors) {

            ValidationUtils.rejectIfEmpty(errors, "name", "name.empty", "姓名不能为空");

            MyBean myBean = (MyBean) target;

            if (myBean.getId() < 0) {
                errors.rejectValue("id", "illegal id", "id not allow <0");
            } else if (myBean.getId() > 100) {
                errors.rejectValue("id", "illegal id", "id not allow >100");
            }

        }
    }


}
